package com.demomaster.quickaccessibility.service;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.demomaster.quickaccessibility.R;
import com.demomaster.quickaccessibility.utils.ClipboardUtil;
import com.demomaster.quickaccessibility.view.adapter.SimpleTreeRecyclerAdapter;
import com.demomaster.quickaccessibility.view.hierarchy.HierarchyView;
import com.demomaster.quickaccessibility.view.hierarchy.QuickAccessNode;
import com.demomaster.quickcompat.listener.OnSingleClickListener;
import com.demomaster.quickcompat.service.QuickFloatingService;
import com.demomaster.quickcompat.service.ServiceHelper;
import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.util.system.QDAppInfoUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.demomaster.quicktreeview.TreeNode;
import cn.demomaster.quicktreeview.TreeViewAdapter;
import cn.demomaster.quicktreeview.TreeData;


/**
 * 页面视图结构查看
 */
public class HierarchyFlotingService extends QuickFloatingService {
    private static final String TAG = "HierarchyFlotingService";
    HierarchyView hierarchyView;
    View dialogView;
    Spinner node_spinner;
    TextView button;
    ViewGroup tab_info, ll_view_info, ll_view_info2;
    RecyclerView recyclerView;
    Button btn_action_touch, btn_action_click, btn_action_longclick, btn_action_input;
    CheckBox cb_tree_view;
    List<TreeNode> mDatas = new ArrayList<>();
    SimpleTreeRecyclerAdapter mAdapter;
    Handler handler = new Handler();
    View.OnClickListener onCaptureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setSelected(!v.isSelected());
            if (!v.isSelected()) {
                //layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                stopCapture();
            } else {
                //layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_FULLSCREEN;
                startCapture();
            }
        }
    };

    @Override
    public void onCreateView(Context context, WindowManager windowManager) {
        hierarchyView = new HierarchyView(context);
        nodeInfoSelectedList = new ArrayList<>();
        //hierarchyView.setBackgroundColor(context.getResources().getColor(R.color.transparent_dark_33));
        int width = DisplayUtil.getScreenWidth(getApplicationContext());
        int height = DisplayUtil.getScreenHeight(getApplicationContext());
        //linearLayout.addView(hierarchyView, new LinearLayout.LayoutParams(width, height));
        hierarchyView.setVisibility(View.GONE);
        button = new TextView(context);
        button.setBackgroundColor(Color.GREEN);
        button.setTextColor(Color.WHITE);
        button.setText("捕获");
        button.setPadding(20, 20, 20, 20);
        button.setOnClickListener(onCaptureClickListener);
        hierarchyView.setOnNodeInfoClickListener(new HierarchyView.OnNodeInfoClickListener() {

            @Override
            public void onClick(List<AccessibilityNodeInfo> nodeInfoList) {
                Log.d(TAG, "onClick: " + nodeInfoList.size());
                ViewGroup.LayoutParams layoutParams = dialogView.getLayoutParams();
                layoutParams.width = DisplayUtil.getScreenWidth(context);
                layoutParams.height = DisplayUtil.getScreenHeight(context);
                dialogView.setLayoutParams(layoutParams);
                nodeInfoSelectedList.clear();
                nodeInfoSelectedList.addAll(nodeInfoList);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    showSelectNodeInfo(nodeInfoList.get(0));
                }
            }
            /*View view = QDActivityManager.getInstance().getCurrentActivity().getWindow().getDecorView().getRootView();
            Bitmap bitmap = ScreenShotUitl.getCacheBitmapFromView(view);
            int top = DisplayUtil.getStatusBarHeight(QDActivityManager.getInstance().getCurrentActivity());
            Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, top, bitmap.getWidth(), bitmap.getHeight() - top, null, false);
            Bitmap bitmap3 = ScreenShotUitl.getCacheBitmapFromView(linearLayout);
            Bitmap bitmap4 = QDBitmapUtil.mergeBitmap(bitmap2, bitmap3);
            File dir = new File(QDFileUtil.getDiskCacheDir(context), "img/abc.jpg");
            QDFileUtil.saveBitmap(bitmap4, dir.getAbsolutePath());*/
        });

        dialogView = LayoutInflater.from(context).inflate(R.layout.layout_floating_hierachy, null);
        dialogView.setBackgroundColor(context.getResources().getColor(com.demomaster.quickcompat.R.color.transparent_dark_55));
        dialogView.setVisibility(View.GONE);

        ll_view_info2 = dialogView.findViewById(R.id.ll_view_info2);
        recyclerView = dialogView.findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //第一个参数  RecyclerView
        //第二个参数  上下文
        //第三个参数  数据集
        //第四个参数  默认展开层级数 0为不展开
        //第五个参数  展开的图标
        //第六个参数  闭合的图标
        mAdapter = new SimpleTreeRecyclerAdapter(dialogView.getContext(),
                mDatas, 1, (currentAccessNode == null ? null : (currentAccessNode.hashCode() + "")));
        mAdapter.setOnTreeNodeClickListener(new TreeViewAdapter.OnTreeNodeClickListener() {
            @Override
            public void onClick(RecyclerView.ViewHolder viewHolder, View view, TreeNode node, int position) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    hierarchyView.setSelectedNodeInfo((AccessibilityNodeInfo) node.getData());
                    //showNodeInfo(viewNodeInfo);
                    showSelectNodeInfo((AccessibilityNodeInfo) node.getData());
                    mAdapter.setFocusedNodeId(node.getData().hashCode() + "");
                }
            }
        });
        recyclerView.setAdapter(mAdapter);
        ll_view_info = dialogView.findViewById(R.id.ll_view_info);
        tab_info = dialogView.findViewById(R.id.tab_info);
        cb_tree_view = dialogView.findViewById(R.id.cb_tree_view);
        cb_tree_view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ll_view_info2.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                if (isChecked) {
                    setTreeData();
                }
            }
        });

        btn_action_touch = dialogView.findViewById(R.id.btn_action_touch);
        btn_action_click = dialogView.findViewById(R.id.btn_action_click);
        btn_action_longclick = dialogView.findViewById(R.id.btn_action_longclick);
        btn_action_input = dialogView.findViewById(R.id.btn_action_input);

        btn_action_touch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentAccessNode != null) {
                    dialogView.setVisibility(View.GONE);
                    button.performClick();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AccessibilityHelper.touchNode(currentAccessNode);
                        }
                    }, 1000);
                }
            }
        });
        btn_action_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccessibilityHelper.clickNode(currentAccessNode);
            }
        });
        btn_action_longclick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccessibilityHelper.longClickNode(currentAccessNode);
            }
        });
        btn_action_input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentAccessNode != null) {
                    Bundle arguments = new Bundle();
                    arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "文字");
                    currentAccessNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                }
            }
        });

        TextView tv_copy = dialogView.findViewById(R.id.tv_copy);
        tv_copy.setOnClickListener(v -> {
            ClipboardUtil.setClip(getApplication(), stringMap.toString());
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
                Toast.makeText(getApplicationContext(), "copy success", Toast.LENGTH_SHORT).show();
            }
        });
        ImageView iv_colse = dialogView.findViewById(R.id.iv_colse);
        iv_colse.setOnClickListener(v -> dialogView.setVisibility(View.GONE));

        //linearLayout.addView(hierarchyViewSection.creatView(context),new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        //linearLayout.addView(dialogView);

        ViewGroup viewGroup = dialogView.findViewById(R.id.rl_bg);
        viewGroup.setOnClickListener(v -> dialogView.setVisibility(View.GONE));

        WindowManager.LayoutParams layoutParams_hierarchyView = new WindowManager.LayoutParams();
        layoutParams_hierarchyView.width = width;
        layoutParams_hierarchyView.height = height;
        //windowManager.addView(hierarchyView, layoutParams_hierarchyView);
        addView(hierarchyView, layoutParams_hierarchyView, true, false, 0, 0);

        WindowManager.LayoutParams layoutParams_button = new WindowManager.LayoutParams();
        layoutParams_button.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams_button.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        //layoutParams_button.copyFrom(layoutParams);
        //windowManager.addView(button, layoutParams_button);
        addView(button, layoutParams_button, true, true, 0, DisplayUtil.getScreenHeight(getApplicationContext()) / 2);

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams_button.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams_button.height = ViewGroup.LayoutParams.MATCH_PARENT;
        //windowManager.addView(dialogView, layoutParams);
        addView(dialogView, layoutParams, true, false, 0, 0);
        //linearLayout.setOnTouchListener(new QDFloatingService.FloatingOnTouchListener(linearLayout));
        Log.d(TAG, "HierarchyFlotingService");
    }

    /**
     * 结束捕获
     */
    private void stopCapture() {
        isCapture = false;
        Log.d(TAG, "stopCapture");
        if (currentAccessNode != null) {
            currentAccessNode.recycle();
            currentAccessNode = null;
        }
        mDatas.clear();
        hierarchyView.setSelectedNodeInfo(null);
        hierarchyView.setVisibility(View.GONE);
        button.setBackgroundColor(Color.GREEN);
        button.setText("捕获");
    }

    public static boolean isCapture;

    /**
     * 开始捕获
     */
    private void startCapture() {
        isCapture = true;
        Log.d(TAG, "startCapture");
        cb_tree_view.setChecked(false);
        Context context = getApplicationContext();
        if (!AccessibilityHelper.isEnable(context, QuickAccessibilityService.class)) {
            //跳转系统自带界面 辅助功能界面
            AccessibilityHelper.startSettintActivity(context);
        } else {
            //setViewPosition(button, Math.min(Math.max(0, point.x), DisplayUtil.getScreenWidth(getApplicationContext())), Math.min(Math.max(0, point.y), DisplayUtil.getScreenHeight(getApplicationContext())));
            //button.setOnTouchListener(new QDFloatingService.FloatingOnTouchListener(button));
            button.setBackgroundColor(Color.RED);
            button.setText("结束");
            hierarchyView.setVisibility(View.VISIBLE);
            if (ServiceHelper.serverIsRunning(context, QuickAccessibilityService.class.getName())) {
                hierarchyView.updateAccessibilityNodeInfo();
                //updateViewLayout(hierarchyView,hierarchyView.getWidth(),hierarchyView.getHeight());
            }
        }
    }

    LinkedHashMap<String, String> stringMap;
    AccessibilityNodeInfo currentAccessNode;
    List<AccessibilityNodeInfo> nodeInfoSelectedList;

    private void showSelectNodeInfo(AccessibilityNodeInfo nodeInfo1) {
        currentAccessNode = nodeInfo1;
        dialogView.setVisibility(View.VISIBLE);
        dialogView.findViewById(R.id.tv_print_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "__________________________________________________________________");
                String str = printInfo(QuickAccessibilityService.instance.getRootInActiveWindow());
                Log.d(TAG, str);
                Log.d(TAG, "__________________________________________________________________");
            }
        });

        node_spinner = dialogView.findViewById(R.id.node_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, nodeInfoSelectedList.stream().map(n -> "控件" + nodeInfoSelectedList.indexOf(n)).toArray(String[]::new));
        node_spinner.setAdapter(adapter);
//        node_spinner.post(new Runnable() {
//            @Override
//            public void run() {
//                node_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                    @Override
//                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                        Log.e(TAG, "onItemSelected");
//                        hierarchyView.setSelectedNodeInfo(nodeInfoSelectedList.get(position));
//                        //showSelectNodeInfo(nodeInfoSelectedList.get(position));
//                        currentAccessNode = nodeInfoSelectedList.get(position);
//                        mAdapter.setFocusedNodeId(Integer.toString(currentAccessNode.hashCode()));
//                        updateTableLayout();
//                    }
//
//                    @Override
//                    public void onNothingSelected(AdapterView<?> parent) {
//
//                    }
//                });
//            }
//        });


//        Rect rect = new Rect();
//        nodeInfo1.getBoundsInScreen(rect);
//        stringMap.put("在屏幕中的位置", "" + rect);
//        nodeInfo1.getBoundsInParent(rect);
//        nodeInfo.setAccessibilityNodeInfo(null);
//        stringMap.put("在父窗体中的位置", "" + rect);

        updateTableLayout();
    }
    List<AccessibilityNodeInfo> currentNodeInfoList = new ArrayList<>();
    void updateTableLayout() {
        QuickAccessNode nodeInfo = new QuickAccessNode(currentAccessNode);
        final Context context = getApplicationContext();
        stringMap = new LinkedHashMap<>();
        PackageInfo packageInfo = QDAppInfoUtil.getPackageInfoByPackageName(context, nodeInfo.getPackageName());
        String appName = null;
        if (packageInfo != null) {
            appName = context.getPackageManager().getApplicationLabel(packageInfo.applicationInfo).toString();// 得到应用名
        }
        stringMap.put("应用名称", appName);
        stringMap.put("页面名称", QuickAccessibilityService.instance.getCurrentActivityName());
        stringMap.put("控件名称", nodeInfo.getClassName());
        stringMap.put("包名", nodeInfo.getPackageName());
        stringMap.put("唯一标识", nodeInfo.getViewIdResourceName());
        stringMap.put("哈希值", nodeInfo.getAccessibilityNodeInfo().hashCode() + "");
        Rect rect = new Rect();
        nodeInfo.getAccessibilityNodeInfo().getBoundsInScreen(rect);
        stringMap.put("坐标", rect + "");
        stringMap.put("包含控件个数", Integer.toString(nodeInfo.getChildCount()));
        stringMap.put("是否焦点", Boolean.toString(nodeInfo.getAccessibilityNodeInfo().isFocused()));
        stringMap.put("是否可用", Boolean.toString(nodeInfo.isEnabled()));
        stringMap.put("是否可点击", Boolean.toString(nodeInfo.isClickable()));
        stringMap.put("isChecked", Boolean.toString(nodeInfo.isChecked()));
        stringMap.put("isSelected", Boolean.toString(nodeInfo.isSelected()));
        stringMap.put("是否显示", Boolean.toString(nodeInfo.isVisibleToUser()));
        stringMap.put("文本", nodeInfo.getText());
        stringMap.put("描述", nodeInfo.getContentDescription());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.d(TAG, "DrawingOrder=" + nodeInfo.getAccessibilityNodeInfo().getDrawingOrder());
            stringMap.put("绘制层级", nodeInfo.getAccessibilityNodeInfo().getDrawingOrder() + "");
        }
        // 获取当前焦点控件
        AccessibilityNodeInfo focusedControl = QuickAccessibilityService.instance.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
        Log.d(TAG, "focusedControl=" + focusedControl);
        // 获取焦点
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            AccessibilityNodeInfo labeledBy = QuickAccessibilityService.instance.getRootInActiveWindow().getLabeledBy();
            Log.d(TAG, "labeledBy=" + labeledBy);
        }

        RadioGroup rg_nav = dialogView.findViewById(R.id.rg_nav);
        rg_nav.removeAllViews();
        final LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        if(currentNodeInfoList==null) {
            currentNodeInfoList = new ArrayList<>();
        }
        if(!currentNodeInfoList.contains(currentAccessNode)) {
            currentNodeInfoList.clear();
            AccessibilityNodeInfo currentNode = nodeInfo.getAccessibilityNodeInfo();
            currentNodeInfoList.add(currentNode);
            while (currentNode != null) {
                currentNode = currentNode.getParent();
                if (currentNode != null) {
                    currentNodeInfoList.add(currentNode);
                }
            }
        }
        for (int i = currentNodeInfoList.size() - 1; i >= 0; i--){
            RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.layout_nav_item, null);
            // 查找最后一个"."的位置
            int lastDotIndex = currentNodeInfoList.get(i).getClassName().toString().lastIndexOf('.');

            String text = null;
            // 检查是否找到了"."
            if (lastDotIndex != -1) {
                // 如果找到了，从"."之后的字符开始截取
                text = currentNodeInfoList.get(i).getClassName().toString().substring(lastDotIndex + 1)+">";
            }
            radioButton.setTag(currentNodeInfoList.get(i));
            radioButton.setText(text);
            radioButton.setId(currentNodeInfoList.get(i).hashCode());
            if(currentAccessNode==currentNodeInfoList.get(i)){
                radioButton.setChecked(true);
            }
            rg_nav.addView(radioButton);
        }

        rg_nav.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < group.getChildCount(); i++) {
                    View child = group.getChildAt(i);
                    if (child instanceof RadioButton && child.getId() == checkedId) {
                        RadioButton radioButton = (RadioButton) child;
                        AccessibilityNodeInfo nodeInfo1 = (AccessibilityNodeInfo) radioButton.getTag();
                        currentAccessNode = nodeInfo1;
                        showSelectNodeInfo(nodeInfo1);
                        mAdapter.setFocusedNodeId(nodeInfo1.hashCode() + "");
                        break;
                    }
                }
            }
        });
        TableLayout tableLayout = dialogView.findViewById(R.id.tab_info);
        //tableLayout.removeAllViews();
        int i = 0;
        for (Map.Entry entry : stringMap.entrySet()) {
            View row = inflater.inflate(R.layout.layout_floating_hierachy_item, null);
            TextView textView = row.findViewById(R.id.tv_name);//new TextView(getApplicationContext());
            TextView tv_content = row.findViewById(R.id.tv_content);//new TextView(getApplicationContext());
            Button btn_copy = row.findViewById(R.id.btn_copy);
            btn_copy.setOnClickListener(new OnSingleClickListener() {
                @Override
                public void onClickEvent(View v) {
                    String str = ((TextView) ((ViewGroup) v.getParent()).findViewById(R.id.tv_content)).getText().toString();
                    ClipboardUtil.setClip(getApplicationContext(), str);
                    Toast.makeText(getApplicationContext(), "copy success", Toast.LENGTH_SHORT).show();
                }
            });

            textView.setText(entry.getKey() + "");
            tv_content.setText(entry.getValue() + "");
            if (i % 2 == 0) {
                row.setBackgroundColor(getResources().getColor(R.color.lightGray));
            }
            //row.addView(linearLayout,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //tableLayout.addView(row);
            i++;
        }
        ((TextView) tableLayout.findViewById(R.id.tv_app_name)).setText(appName);
        ((TextView) tableLayout.findViewById(R.id.tv_package_name)).setText(nodeInfo.getPackageName());
        ((TextView) tableLayout.findViewById(R.id.tv_activity_name)).setText(QuickAccessibilityService.instance.getCurrentActivityName());
        ((TextView) tableLayout.findViewById(R.id.tv_view_class)).setText(nodeInfo.getClassName());
        ((TextView) tableLayout.findViewById(R.id.tv_view_id)).setText(nodeInfo.getViewIdResourceName());
        ((TextView) tableLayout.findViewById(R.id.tv_text)).setText(nodeInfo.getText());
        ((TextView) tableLayout.findViewById(R.id.tv_description)).setText(nodeInfo.getContentDescription());
        ((TextView) tableLayout.findViewById(R.id.tv_focusable)).setText(Boolean.toString(nodeInfo.getAccessibilityNodeInfo().isFocused()));
        ((TextView) tableLayout.findViewById(R.id.tv_clickable)).setText(Boolean.toString(nodeInfo.isClickable()));
        ((TextView) tableLayout.findViewById(R.id.tv_isChecked)).setText(Boolean.toString(nodeInfo.isChecked()));
        ((TextView) tableLayout.findViewById(R.id.tv_isSelected)).setText(Boolean.toString(nodeInfo.isSelected()));
        ((TextView) tableLayout.findViewById(R.id.tv_isEnabled)).setText(Boolean.toString(nodeInfo.isEnabled()));
        ((TextView) tableLayout.findViewById(R.id.tv_isClickable)).setText(Boolean.toString(nodeInfo.isClickable()));
        ((TextView) tableLayout.findViewById(R.id.tv_isVisibleToUser)).setText(Boolean.toString(nodeInfo.isVisibleToUser()));
        ((TextView) tableLayout.findViewById(R.id.tv_child_count)).setText(Integer.toString(nodeInfo.getChildCount()));
        Rect rect2 = AccessibilityHelper.getBundsInScreen(nodeInfo.getAccessibilityNodeInfo());
        ((TextView) tableLayout.findViewById(R.id.tv_position)).setText(rect2==null?"":rect2.toString());
    }

    /**
     * 打印node信息
     *
     * @param rootInActiveWindow
     */
    private String printInfo(AccessibilityNodeInfo rootInActiveWindow) {
        return getNodeInfoString(rootInActiveWindow, 0);
    }

    private String getNodeInfoString(AccessibilityNodeInfo rootInActiveWindow, int level) {
        StringBuilder stringBuilder = new StringBuilder();
        if (rootInActiveWindow != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    String levelStr = "";
                    for (int i = 0; i < level; i++) {
                        levelStr += "——";
                    }
                    stringBuilder.append(
                            levelStr + "," + rootInActiveWindow.getClassName()
                                    + ",id=" + rootInActiveWindow.getViewIdResourceName()
                                    + ",text=" + rootInActiveWindow.getText()
                                    + ",descption=" + rootInActiveWindow.getContentDescription()
                                    + ",getDrawingOrder=" + rootInActiveWindow.getDrawingOrder()
                                    + "\n");
                }
                int count = rootInActiveWindow.getChildCount();
                for (int i = 0; i < count; i++) {
                    stringBuilder.append(getNodeInfoString(rootInActiveWindow.getChild(i), level + 1));
                }
            }
        }
        return stringBuilder.toString();
    }

    TreeData.TreeDataConverter treeDataConverter = new TreeData.TreeDataConverter<AccessibilityNodeInfo>() {
        @Override
        public String getNodePid(AccessibilityNodeInfo node) {
            return node == null ? "" : (node.getParent().hashCode() + "");
        }

        @Override
        public String getNodeId(AccessibilityNodeInfo node) {
            return node == null ? "" : (node.hashCode() + "");
        }

        @Override
        public String getNodeLable(AccessibilityNodeInfo node) {
            return node == null ? "" : (node.getClassName() + (node.getChildCount() > 0 ? ("（" + node.getChildCount() + "）") : ""));
        }

        @Override
        public Object getBindData(AccessibilityNodeInfo node) {
            return node;
        }

        @Override
        public List<AccessibilityNodeInfo> getNodeChild(AccessibilityNodeInfo node) {
            List<AccessibilityNodeInfo> childs = new ArrayList<>();
            if (node != null) {
                for (int i = 0; i < node.getChildCount(); i++) {
                    childs.add(node.getChild(i));
                }
            }
            return childs;
        }
    };

    /**
     * 設置树状结构视图数据
     */
    private void setTreeData() {
        if (currentAccessNode != null) {
            mAdapter.setFocusedNodeId(currentAccessNode.hashCode() + "");
        }
        if (mDatas.size() == 0) {
            long t1 = System.currentTimeMillis();
            List<AccessibilityNodeInfo> list = new ArrayList<>();
            list.add(QuickAccessibilityService.instance.getRootInActiveWindow());
            TreeData treeData = new TreeData<AccessibilityNodeInfo>();
            treeData.setData(list, treeDataConverter);
            mDatas.clear();
            mDatas.addAll(treeData.getData());
            mAdapter.setData(mDatas);
            long t2 = System.currentTimeMillis();
            Log.d(TAG, "耗时：" + (t2 - t1));
        }
    }

//    @Override
//    public PointF getOriginPoint() {
//        return new PointF(0, DisplayUtil.getScreenHeight(getApplicationContext()) / 2f);
//    }
//
//    @Override
//    public boolean getTouchAble() {
//        return true;
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeView(button);
        removeView(hierarchyView);
        removeView(dialogView);
    }
}
